layui.config({
    base: $config.resUrl + '/web/common/js/'//定义基目录
}).extend({
    ajaxExtention: 'ajaxExtention',//加载自定义扩展，每个业务js都需要加载这个ajax扩展
    $tool: 'tool',
    $api: 'api'
}).use(['form', 'layer', 'upload', 'ajaxExtention', '$tool', '$api'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        $ = layui.jquery,
        upload = layui.upload,
        $tool = layui.$tool,
        $api = layui.$api;


    /**
     * 页面初始化
     * */
    function init() {
        //初始化用户信息
        initUserInfo();
        //初始化上传控件
        // initUploadComponent();
    }

    init();

    /**
     * 初始化上传控件
     * */
    function initUploadComponent() {
        //执行实例
        var uploadInst = upload.render({
            elem: '#userFaceUpload' //绑定元素
            , url: $tool.getContext() + '/upload' //上传接口
            , auto: false //选择文件后不自动上传
            , bindAction: '#userInfoSubmit' //指向一个按钮触发上传
            , accept: 'images'
            , size: '1024'//限制大小,单位kb
            , data: {type: 'userFace'}//上传业务类型，后台会根据这个值将文件放入相应文件夹下
            , choose: function (obj) {
                //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                obj.preview(function (index, file, result) {
                    //图片预览,result是图片base64编码
                    $('#userFace').css('background-image', 'url(' + result + ')');
                });
            }
            , done: function (res) {
                //上传完毕回调
                console.log(res);
            }
            , error: function () {
                //请求异常回调
                layer.msg("上传失败");
            }
        });
    }

    /**
     * 初始化用户信息
     * */
    function initUserInfo() {
        var user = JSON.parse(window.localStorage.getItem('user'));
        if (user) {
            $("[name='id']").val(user.id);
            $("[name='username']").val(user.username);
            $("[name='trueName']").val(user.trueName);
            $("[name='email']").val(user.email);
        }
    }

    /**
     * 表单提交
     * */
    form.on("submit(editUser)", function (data) {
        var id = data.field.id;
        var username = data.field.username;
        var trueName = data.field.trueName;
        var email = data.field.email;

        //请求
        var url = $tool.getContext() + '/user/update';
        var req = {
            id: id,
            username: username,
            trueName: trueName,
            email: email,
            headUrl: ''
        };

        $api.doPost('/user/update', req, function (res) {
            if (res.code == 200) {
                layer.msg("更新成功！", {time: 1000}, function () {
                    window.localStorage.setItem("user", JSON.stringify(res.data));
                });
            } else {
                layer.msg("更新失败！", {time: 1000});
            }
        });
        return false;
    })
});